<?php

namespace Users\Login\Helper;

use Pinenut\User\Profile;
use Pinenut\User\Auth\EmailPassword as Auth;
use Pinenut\Form;
use Users\Login\EmailPasswordFormConfig as FormConfig;

/**
 * Обработчик формы локальной регистрации
 * Примесь для действия
 * 
 * @author kosh
 *        
 */
trait EmailPassword {
	function auth() {
		$formConfig = FormConfig::get ();
		$formConfig ['htmlOptions'] ['action'] = $this->url ( 'users.login.emailPassword' );
		
		$form = new Form ( $this->request->getSessionId (), 'emailPasswordLogin', $formConfig );
		
		if ($this->request->isPost() && $this->request->isAjax()) {
			$form->process($this->request->params(), true);
			$this->response->content = $form->render();
			$this->response->noRender(true);
			return;
		} else if ($this->request->isPost () && ! $this->request->onlyRender) {
			if (! $form->process ( $this->request->params () )) {
				$this->response->form = $form;
				return;
			}
			// уже проверили что всё ок
			// создаём пользователя
			$data = $form->getValues ();
			$auth = new Auth ();
			$auth->email = $data ['email'];
			$auth->setPassword ( $data ['password'] );
			
			$auth = $auth->auth ();
			
			if ($auth) {
				$form->flush();
				return $auth;
			}
			// пробовали, но не прошли аутентификацию
			// ругаемся
			$form->addErrors ( 'password', 'Invalid Password' );
		}
		$this->response->form = $form;
	}
}